var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var cors = require('cors');

var routes = require('./routes/index');
var show = require('./routes/show');
var manage = require('./routes/manager');
var jspDev = require('./routes/jsp-dev');
var ifResp = require('./routes/if-response');
var helper = require('./routes/if-helper');
var logout = require('./routes/logout');

var app = express();
var basicAuth = require('basic-auth');
var authHelper = require('./config/auth-manager');

function getNoQueryUrl(originalUrl){
    let queryStartPos = originalUrl.indexOf('?');
    if(~queryStartPos){
        return originalUrl.substring(0, queryStartPos);
    }
    return originalUrl;
};
var auth = function (req, resp, next) {
    function unauthorized(resp) {
        // 认证框要求输入用户名和密码的提示语
        resp.set('WWW-Authenticate', 'Basic realm=Input UserName&Password');
        return resp.sendStatus(401);
    }

    var user = basicAuth(req), authObj = authHelper.getAuthObj(), nowUserInfo;

    if (!user || !user.name || !user.pass) {
        return unauthorized(resp);
    }

    // 简单粗暴，用户名直接为User，密码直接为Password
    if ((nowUserInfo = authObj[user.name]) && authObj[user.name].pass === user.pass) {
        let path = getNoQueryUrl(req.url),
            isAdminPath = path === '/admin',
            isLogoutPath = path === '/logout',
            pagePath = /^((?:view|manage)-[^/]+)(?:\/.+)?/.exec(path);
        if(isLogoutPath){
            if(req.cookies['LOP'] !== '1'){
                resp.cookie('LOP', '1', {httpOnly:true, path:'/'});
                return unauthorized(resp);
            }
        }

        if(isAdminPath && !nowUserInfo.isAdmin){
            return unauthorized(resp);
        }
        if(!isAdminPath && !isLogoutPath && pagePath && !~nowUserInfo.auth.indexOf(pagePath[1]) && path.length > 1){
            return authHelper.validPath(path) ? unauthorized(resp) : resp.sendStatus(404);
        }
        resp.cookie('lg-pin', `${user.name}|${authObj[user.name].name}`, {httpOnly:true, path:'/'});
        req.authApps = nowUserInfo.authApps;
        return next();
    } else {
        return unauthorized(resp);
    }
};

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json({limit : '102400kb'}));
app.use(bodyParser.urlencoded({extended: false, limit : '102400kb'}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));


app.use(/\/view-[^/]+/, auth, show);
app.use(/\/manage-[^/]+/, auth, manage);
app.use(/\/jspdev-[^/]+/, auth, jspDev);
app.use('/logout', auth, logout);

app.use(/\/api-[^/]+\/.+/, cors(), ifResp);
app.use(/.+\.json/, cors(), ifResp);

app.use('/helper', helper);

app.use('/', auth, routes);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function (err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});


const bearcat = require('bearcat'),
    beanUtil = require('./utils/beanUtil'),
    contextPath = require.resolve('./context.json');
// 初始化设置BeanUtil
beanUtil.initContext(bearcat);

// 开始加载服务器的beans
bearcat.createApp([contextPath], void(0));

bearcat.start(function() {
    const socketServer = require('./socket/socket-server').createServer();

    require('./mappings/socket-mapping').registerSocketService(socketServer);

    socketServer.listen(3333);

    socketServer.on('close', function(){});

});

module.exports = app;
